#!coding=utf-8
from django.http import HttpResponse
from technology.models import Technology,Date_link,Image,UploadFile,MyUserModel
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from restore.settings import MEDIA_ROOT
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
import json,random,xlwt,time,os
import sys
reload(sys)
sys.setdefaultencoding('utf8')
@csrf_exempt
def loginValidation(request):
    name=request.POST.get('username')
    password=request.POST.get('password')
    if not name or not password:
        info='用户名或者密码为空'
        return render_to_response('login.html',{'info':info},context_instance=RequestContext(request))
    try:
        user=MyUserModel.objects.get(username=name,password=password)
        if user is not None:
            request.session['user']=user
        return HttpResponseRedirect('/')
    except:
        info='用户名或者密码错误'
        return render_to_response('login.html',{'info':info},context_instance=RequestContext(request))

def p_page():
    return 7


def homepage(request):
    user=request.session.get('user')
    if user:
        per_page=p_page()
        technology_list = Technology.objects.all()
        paginator = Paginator(technology_list, per_page)
        page = request.GET.get('page')
        try:
            contacts = paginator.page(page)
        except PageNotAnInteger:
            contacts = paginator.page(1)
        except EmptyPage:
            contacts = paginator.page(paginator.num_pages)
        return render_to_response('index.html',{'paginator':paginator,'contacts':contacts,'user':user},context_instance=RequestContext(request))
    else:
        return render_to_response('login.html',context_instance=RequestContext(request))
        
@csrf_exempt
def tecCompare(request):
    info=''
    value=request.POST.getlist('idarr')
    list_tec=[]
    try:
        for v in value:
            technology= Technology.objects.get(id='%s' %v)
            list_tec.append(technology.return_dict())
        info='success'
    except Exception, e:
        info='error'
    temp= json.dumps({'info':info,'result':list_tec})
    return HttpResponse(temp)

def technologyAdapt(request,param):
    technology= Technology.objects.get(id=param)
    technology.mature='%s' %technology.mature
    user=request.session.get('user')
    return render_to_response('tec-adapt.html',{'technology':technology,'user':user},context_instance=RequestContext(request))

def technologyAapply(request,param):
    technology= Technology.objects.get(id=param)
    data_link=Date_link.objects.filter(technology=technology)
    images=Image.objects.filter(technology=technology)
    uploadfile=UploadFile.objects.filter(technology=technology)
    user=request.session.get('user')
    for file in uploadfile:
        file.filename=file.upload_file.name.split('/')[-1]
        file.save()
    return render_to_response('tec-apply.html',{'user':user,'technology':technology,'data_link':data_link,'images':images,'uploadfile':uploadfile},context_instance=RequestContext(request))

def technologyIntroduce(request,param):
    technology= Technology.objects.get(id=param)
    user=request.session.get('user')
    return render_to_response('tec-intro.html',{'technology':technology,'user':user},context_instance=RequestContext(request))

def technologyAdd(request):
    user=request.session.get('user')
    return render_to_response('tec-add.html',{'user':user},context_instance=RequestContext(request))

@csrf_exempt
def tecModifySubmit(request):
    tec_id=request.POST.get('id')
    tec_name=request.POST.get('tec_name')
    tec_type=request.POST.get('tec_type')
    tec_info=request.POST.get('tec_info')
    tec_second_contrller=request.POST.get('tec_second_contrller')
    tec_mature=request.POST.get('tec_mature')
    tec_time=request.POST.get('tec_time')
    tec_input_time=request.POST.get('tec_input_time')
    tec_cost=request.POST.get('tec_cost')
    tec_input_cost=request.POST.get('tec_input_cost')
    tec_poll_density=request.POST.get('tec_poll_density')
    tec_adapt=request.POST.get('tec_adapt')
    tec_limit=request.POST.get('tec_limit')
    tec_internation=request.POST.get('tec_internation')
    tec_case=request.POST.get('tec_case')
    poll_type=request.POST.get('poll_type')
    poll_name=request.POST.get('poll_name')
    poll_media=request.POST.get('poll_media')
    poll_dispose=request.POST.get('poll_dispose')
    if tec_mature=='成熟':
        tec_mature=True
    else:
        tec_mature=False
    technology=Technology.objects.get(id=tec_id)
    technology.name=tec_name
    technology.type=tec_type
    technology.info=tec_info
    technology.mature=tec_mature
    technology.adaptation=tec_adapt
    technology.limitation=tec_limit
    technology.internation_info=tec_internation
    technology.case_info=tec_case
    technology.second_control_points=tec_second_contrller
    technology.refer_time=tec_time
    technology.input_time=tec_input_time
    technology.input_cost=tec_input_cost
    technology.cost=tec_cost
    technology.pollutant_concentration=tec_poll_density
    technology.pollutant_name=poll_name
    technology.dispose=poll_dispose
    technology.media=poll_media
    technology.pollutant_type=poll_type
    data_links=Date_link.objects.filter(technology=technology)
    images=Image.objects.filter(technology=technology)
    uploadfiles=UploadFile.objects.filter(technology=technology)
    oldimages=request.POST.getlist('oldImage')
    oldFiles=request.POST.getlist('oldfile')
    for link in data_links:
        if link:
            link.delete()
    for image in images:
        if image.image not in oldimages:
            os.remove(MEDIA_ROOT+image.image.name)
            image.delete()
    for upload in uploadfiles:
        if upload.upload_file.name not in oldFiles:
            os.remove(MEDIA_ROOT+upload.upload_file.name)
            upload.delete()
    files= request.FILES.getlist('file','')
    links=request.POST.getlist('link')
    images = request.FILES.getlist('image','')
    imagenames=request.POST.getlist('newimagename')
    for image in images:
        imagename=imagenames[images.index(image)]
        imagemodel=Image.objects.create(technology=technology,image=image,imagename=imagename)

    for link in links:
        dateLink=Date_link.objects.create(technology=technology,link=link)

    for file in files:
        upload=UploadFile.objects.create(technology=technology,upload_file=file)
    technology.save()
    return HttpResponseRedirect('/')

@csrf_exempt
def tecAddSubmit(request):
    tec_name=request.POST.get('tec_name')
    tec_type=request.POST.get('tec_type')
    tec_info=request.POST.get('tec_info')
    tec_second_contrller=request.POST.get('tec_second_contrller')
    tec_mature=request.POST.get('tec_mature')
    tec_time=request.POST.get('tec_time')
    tec_input_time=request.POST.get('tec_input_time')
    tec_cost=request.POST.get('tec_cost')
    tec_input_cost=request.POST.get('tec_input_cost')
    tec_poll_density=request.POST.get('tec_poll_density')
    tec_adapt=request.POST.get('tec_adapt')
    tec_limit=request.POST.get('tec_limit')
    tec_internation=request.POST.get('tec_internation')
    tec_case=request.POST.get('tec_case')
    poll_type=request.POST.get('poll_type')
    poll_name=request.POST.get('poll_name')
    poll_media=request.POST.get('poll_media')
    poll_dispose=request.POST.get('poll_dispose')
    if tec_mature=='True':
        tec_mature=True
    else:
        tec_mature=False
    technology=Technology.objects.create(name=tec_name,type=tec_type,info=tec_info,mature=tec_mature,
                                         adaptation=tec_adapt,limitation=tec_limit,
                                         internation_info=tec_internation,case_info=tec_case,
                                         second_control_points=tec_second_contrller,refer_time=tec_time,
                                         input_time=tec_input_time,input_cost=tec_input_cost,cost=tec_cost,
                                         pollutant_concentration=tec_poll_density,pollutant_name=poll_name,
                                         dispose=poll_dispose,media=poll_media,pollutant_type=poll_type)
    files= request.FILES.getlist('file','')
    links=request.POST.getlist('link')
    images = request.FILES.getlist('image','')
    imagenames=request.POST.getlist('imagename')
    for image in images:
        imagename=imagenames[images.index(image)]
        imagemodel=Image.objects.create(technology=technology,image=image,imagename=imagename)

    for link in links:
        dateLink=Date_link.objects.create(technology=technology,link=link)

    for file in files:
        upload=UploadFile.objects.create(technology=technology,upload_file=file)

    return HttpResponseRedirect('/')


@csrf_exempt
def tecFilter(request):
    if request.method=='POST':
        pollutant_type=request.POST.get('pollutant_type')
        pollutant_media=request.POST.get('pollutant_media')
        pollutant_dispose=request.POST.get('pollutant_dispose')
        tec_time=request.POST.get('time')
        cost=request.POST.get('cost')
        tec_mature=request.POST.get('tec_mature')
        tec_poll_density=request.POST.get('tec_poll_density')
        type_load=request.session.get('list')
        if type_load:
            TECHNOLOGY=type_load
        else:
            TECHNOLOGY=Technology.objects.all()
        if tec_mature:
            if tec_mature=='True':
                tec_mature=True
            else:
                tec_mature=False
            TECHNOLOGY = TECHNOLOGY.filter(mature=tec_mature)

        if tec_time:
            TECHNOLOGY= TECHNOLOGY.filter(refer_time=tec_time)

        if cost:
            TECHNOLOGY= TECHNOLOGY.filter(cost=cost)
        if tec_poll_density:
            density_technology=[]

            for tec in TECHNOLOGY:
                if tec_poll_density in tec.pollutant_concentration:
                    density_technology.append(tec)
            TECHNOLOGY=density_technology
        if pollutant_dispose:
            dispose_technology=[]
            for tec in TECHNOLOGY:
                if pollutant_dispose in tec.dispose:
                    dispose_technology.append(tec)
            TECHNOLOGY=dispose_technology
        if pollutant_media:
            media_technology=[]
            for tec in TECHNOLOGY:
                if pollutant_media in tec.media:
                    media_technology.append(tec)
            TECHNOLOGY=media_technology
        if pollutant_type:
            type_technology=[]
            for tec in TECHNOLOGY:
                if pollutant_type in tec.pollutant_type:
                    type_technology.append(tec)
            TECHNOLOGY=type_technology
        if type_load:
            del request.session['list']
        request.session['contacts']=TECHNOLOGY

    if request.method=='GET':
        TECHNOLOGY=request.session.get('contacts')
    per_page=p_page()
    paginator = Paginator(TECHNOLOGY, per_page)
    page = request.GET.get('page')
    try:
        contacts = paginator.page(page)
    except PageNotAnInteger:
        contacts = paginator.page(1)
    except EmptyPage:
        contacts = paginator.page(paginator.num_pages)
    user=request.session.get('user')
    return render_to_response('index.html',{'paginator':paginator,'contacts':contacts,'user':user},context_instance=RequestContext(request))

def tecDelete(request,param):
    technology=Technology.objects.get(id=param)
    date=Date_link.objects.filter(technology=technology)
    images=Image.objects.filter(technology=technology)
    uploadfiles=UploadFile.objects.filter(technology=technology)
    for datelink in date:
        if datelink:
            datelink.delete()

    for image in images:
        if image:
            image.delete()
            os.remove(MEDIA_ROOT+image.image.name)

    for upload in uploadfiles:
        if upload:
            upload.delete()
            os.remove(MEDIA_ROOT+upload.upload_file.name)

    technology.delete()
    return HttpResponseRedirect('/')

@csrf_exempt
def technologyLoad(request):
    types=request.POST.get('type')
    request_page=request.POST.get('page')
    per_page=p_page()
    lists=[]
    technology_list=Technology.objects.all()
    if types!='全部':
        technology_list=technology_list.filter(type=types)
    technology=technology_list.order_by('id')[(eval(request_page)-1)*per_page:(eval(request_page)-1)*per_page+per_page]
    tec_count= len(technology_list)
    request.session['list']=technology_list
    page_number=tec_count%per_page
    if page_number==0:
        page_count=tec_count/per_page
    else:
        page_count=tec_count/per_page+1
    for tec in technology:
        lists.append(tec.return_dict())
    temp= json.dumps({'info':'success','contacts':lists,'page_count':page_count})
    return HttpResponse(temp)

def tecModify(request,param):
    technology=Technology.objects.get(id=param)
    data_link=Date_link.objects.filter(technology=technology)
    images=Image.objects.filter(technology=technology)
    uploadfiles=UploadFile.objects.filter(technology=technology)
    for file in uploadfiles:
        file.filename=file.upload_file.name.split('/')[-1]
        file.save()
    user=request.session.get('user')
    return render_to_response('tec-modify.html',{'user':user,'technology':technology,'data_link':data_link,'images':images,'uploadfiles':uploadfiles},context_instance=RequestContext(request))

@csrf_exempt
def tecExport(request):
    value=request.POST.getlist('list')
    list_tec=[]
    try:
        for v in value:
            if v!='on':
                technology= Technology.objects.get(id='%s' %v)
                list_tec.append(technology)
        info='success'
    except Exception, e:
        info='error'
    wbk=xlwt.Workbook()
    sheet=wbk.add_sheet(u'修复技术信息列表')
    sheet.write(0,0,u'编号')
    sheet.write(0,1,u'技术名称')
    sheet.write(0,2,u'污染物种类')
    sheet.write(0,3,u'介质')
    sheet.write(0,4,u'时间')
    sheet.write(0,5,u'成本')
    sheet.write(0,6,u'污染物浓度')
    sheet.write(0,7,u'成熟度')
    row=1
    for tec in list_tec:
        sheet.write(row,0,tec.id)
        sheet.write(row,1,tec.name)
        sheet.write(row,2,tec.type)
        sheet.write(row,3,tec.media)
        sheet.write(row,4,tec.refer_time)
        sheet.write(row,5,tec.cost)
        sheet.write(row,6,tec.pollutant_concentration)
        if tec.mature==True:
            sheet.write(row,7,u'成熟')
        else:
            sheet.write(row,7,u'不成熟')
        row+=1
    media=os.path.join(os.path.dirname(__file__), 'medias/').replace('\\', '/')
    filename=u'污染场地修复技术列表.xls'
    wbk.save(filename)
    fp = open(filename, 'rb')
    data = fp.read()
    fp.close()
    filename=r'污染场地修复技术列表.xls'
    response = HttpResponse(data,mimetype='application/octet-stream')
    response['Content-Encoding'] = 'utf-8'
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    return response

def read_pdf(request):
    return render_to_response('pdf.html')

def loginhtml(request):
    return render_to_response('login.html',context_instance=RequestContext(request))

# def registerhtml(request):
#     return render_to_response('register.html',context_instance=RequestContext(request))

def userList(request):
    users=MyUserModel.objects.filter(is_staff=False)
    user=request.session.get('user')
    return render_to_response('user-list.html',{'users':users,'user':user},context_instance=RequestContext(request))

def userModifyList(request,params):
    user=MyUserModel.objects.get(id=params)
    useradmin=request.session.get('user')
    return render_to_response('user-modify.html',{'user':user,'useradmin':useradmin},context_instance=RequestContext(request))

def userDeleteList(request,params):
    user=MyUserModel.objects.get(id=params)
    user.delete()
    return HttpResponseRedirect('/user-list/')

def userAdd(request):
    user=request.session.get('user')
    return render_to_response('user-add.html',{'user':user},context_instance=RequestContext(request))

@csrf_exempt
def modifyUserSubmit(request):
    username=request.POST.get('username')
    password=request.POST.get('password')
    id=request.POST.get('id')
    if not username or not password:
        info='不能用空选项'
        return render_to_response('user-modify.html',{'info':info},context_instance=RequestContext(request))
    user=MyUserModel.objects.get(id=id)
    user.username=username
    user.password=password
    user.save()
    return HttpResponseRedirect('/user-list/')

def pswModify(request):
    user=request.session.get('user')
    return render_to_response('psw-modify.html',{'user':user},context_instance=RequestContext(request))

@csrf_exempt
def pswModifySubmit(request):
    password=request.POST.get('password')
    repassword=request.POST.get('repassword')
    if not password or not repassword:
        info='不能有空选项'
        return render_to_response('psw-modify.html',{'info':info},context_instance=RequestContext(request))
    if len(password)<5:
        info='密码不能小于五位数'
        return render_to_response('psw-modify.html',{'info':info},context_instance=RequestContext(request))
    if password!=repassword:
        info='两次输入的密码不一样！'
        return render_to_response('psw-modify.html',{'info':info},context_instance=RequestContext(request))
    try:
        user=request.session.get('user')
        user.password=password
        user.save()
    except:
        return HttpResponse(u'请求来源有误！')
    return HttpResponseRedirect('/')

@csrf_exempt
def registeValidate(request):
    username=request.POST.get('username')
    password=request.POST.get('password')
    repassword=request.POST.get('repassword')
    email=request.POST.get('email')
    if not username or not password or not email:
        info='不能有空选项'
        return render_to_response('register.html',{'info':info},context_instance=RequestContext(request))
    if password!=repassword:
        info='两次输入的密码不一致'
        return render_to_response('register.html',{'info':info},context_instance=RequestContext(request))
    try:
        User.objects.get(username=username)
        info='用户名被占用'
        return render_to_response('register.html',{'info':info},context_instance=RequestContext(request))
    except:
        pass
    try:
        User.objects.get(email__exact=email)
        info='邮箱已占用'
        return render_to_response('register.html',{'info':info},context_instance=RequestContext(request))
    except:
        pass
    u=User.objects.create_user(username=username,password=password,email=email)
    u.is_active=True
    u.save()
    info='注册成功！请登陆'
    return render_to_response('login.html',{'infos':info},context_instance=RequestContext(request))

def logout(request):
    del request.session['user']
    return HttpResponseRedirect('/')

@csrf_exempt
def addUserSubmit(request):
    username=request.POST.get('username')
    password=request.POST.get('password')
    repassword=request.POST.get('repassword')
    if not username or not password or not repassword:
        info='不能有空选项'
        return render_to_response('user-add.html',{'info':info},context_instance=RequestContext(request))
    if password!=repassword:
        info='两次输入的密码不一致'
        return render_to_response('user-add.html',{'info':info},context_instance=RequestContext(request))
    user=MyUserModel.objects.filter(username=username)
    if user:
        info='用户名已经存在'
        return render_to_response('user-add.html',{'info':info},context_instance=RequestContext(request))
    user=MyUserModel.objects.create(username=username,password=password,is_staff=False)
    if user:
        return HttpResponseRedirect('/user-list/')